// 使用express框架，后续可以考虑使用expressCli生成后端目录结构
const express = require('express');

const bodyParser = require('body-parser');

const indexRoute = require('./routers/index');

const session = require('express-session');

const app = express();

// 全局引入session
app.use(session(
    {
        secret: '123456',   //对session id 相关的cookie 进行签名
        resave: false,
        saveUninitialized: true,  // 是否保存未初始化的会话
        cookie: { maxAge:1000*60*60*24 }  // 设置session的有效时长，单位ms
    }
))
// 为所有请求设置，解决跨域问题
app.all("*", function(req, res, next) {
    if (!req.get("Origin")) return next();
    // use "*" here to accept any origin
    res.set("Access-Control-Allow-Origin","*");
    res.set("Access-Control-Allow-Methods", "GET");
    res.set("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
    // res.set('Access-Control-Allow-Max-Age', 3600);
    if ("OPTIONS" === req.method) return res.sendStatus(200);
    next();
});
// 全局设置post参数解析
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(indexRoute);

// express中间件，想象一下自来水处理过程
const port = process.env.PORT || 5678;



app.listen(port,()=>{
    console.log('serve is running....')
})